package com.smiier.skin;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cn.o.app.json.JsonUtil;
import cn.o.app.media.PickPhotoTask;
import cn.o.app.media.PickPhotoTask.PickPhotoListener;
import cn.o.app.media.TakePhotoTask;
import cn.o.app.media.TakePhotoTask.TakePhotoListener;
import cn.o.app.ui.FlowLayout;
import cn.o.app.ui.OActionSheet;
import cn.o.app.ui.OActionSheet.OActionItem;
import cn.o.app.ui.OActionSheet.OnActionItemClickListener;
import cn.o.app.ui.OAlert;
import cn.o.app.ui.OAlert.OAlertListener;
import cn.o.app.ui.ODatePicker;
import cn.o.app.ui.ODatePicker.OnPickDateListener;
import cn.o.app.ui.OImageView;
import cn.o.app.util.ODateFormat;
import cn.skinapp.R;

import com.evan.common.handler.RequestHandler;
import com.evan.common.handler.callback.HandlerCallback;
import com.evan.common.widget.ItemView;
import com.evan.common.widget.LoadingProgressExt;
import com.smiier.skin.constant.Constant;
import com.smiier.skin.extra.UserExtra;
import com.smiier.skin.intercept.RequestTaskIntercept;
import com.smiier.skin.net.entity.User;
import com.smiier.skin.ui.BasicActivity;
import com.smiier.skin.util.GlobalSettings;
import com.smiier.skin.utils.CommonUtility;

/**
 * @{# CreateQuestionActivity.java Create on 2014-6-3 下午2:11:38
 * 
 * @author <a href="mailto:evan0502@qq.com">Evan</a>
 * @version 1.0
 * 
 * 
 *          此界面用于创建问题，编辑问题，创建病案和修改病案
 */

@SuppressLint({ "InflateParams", "ClickableViewAccessibility" })
public class CreateQuestionActivity extends BasicActivity {

	LayoutInflater inflater;

	private HashMap<View, String> img_path;

	private FlowLayout ll_imgs;

	private LinearLayout ll_root;

	private LinearLayout ll_more_info;

	private EditText edit_content;

	private ImageView img_arrow;

	private ItemView mBuweiItemView;

	private ItemView mBingshiItemView;

	private ItemView mYaowuguominItemView;

	private ItemView mPutongguominItemView;

	private ItemView mJiarenItemView;

	private Button mBtnAge;

	private RadioGroup mRadioGroupSex;
	private ItemView mDoctorSelector;
	private TextView img_upload_pic;

	String buwei, content, mAge;
	private StringBuilder sbPath;

	private boolean isBingli, isEditBingli, isEditQuestion,
			isCreateCost2Doctor;
	private JSONObject mr_question, doctorInfo;

	private HashMap<String, String> imgs;
	private LinearLayout mTextShow;
	private final static int REQUEST_FOR_SOLVE_PROBLEM = 10;
	private RelativeLayout mDoctorSelector1;
	private TextView mDoctorName;
	private TextView mDoctorProfession;
	private TextView mDoctorHospital;
	private TextView mDoctorPrice;
	private Drawable mDrawable;
	private User mUser;
	private final static int REQUEST_FOR_PAY_SUCCESS = 100;
	OImageView mImg;
	boolean mReward = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_create_question);
		String doctorInfoFromDoctorDetail = getIntent().getStringExtra(
				Constant.IDENTITY_KEY_DOCTOR_INFO);

		ll_imgs = (FlowLayout) findViewById(R.id.ll_imgs);
		ll_root = (LinearLayout) findViewById(R.id.ll_root);
		ll_more_info = (LinearLayout) findViewById(R.id.ll_more_info);
		edit_content = (EditText) findViewById(R.id.edit_content);
		img_arrow = (ImageView) findViewById(R.id.img_arrow);
		mBuweiItemView = (ItemView) findViewById(R.id.itemview_buwei);
		mBingshiItemView = (ItemView) findViewById(R.id.itemview_bingshi);
		mYaowuguominItemView = (ItemView) findViewById(R.id.itemview_yaowuguomin);
		mPutongguominItemView = (ItemView) findViewById(R.id.itemview_putongguomin);
		mJiarenItemView = (ItemView) findViewById(R.id.itemview_jiaren);
		mBtnAge = (Button) findViewById(R.id.btn_age);
		mRadioGroupSex = (RadioGroup) findViewById(R.id.radio_group_sex);
		img_upload_pic = (TextView) findViewById(R.id.img_upload_pic);
		mTextShow = findViewById(R.id.toast_text_show, LinearLayout.class);
		mDoctorSelector = findViewById(R.id.select_doctor, ItemView.class);
		mDoctorSelector1 = findViewById(R.id.select_doctor_1,
				RelativeLayout.class);
		mDoctorName = findViewById(R.id.doctor_name, TextView.class);
		mDoctorProfession = findViewById(R.id.doctor_professional,
				TextView.class);
		mImg = findViewById(R.id.img_doctor_icon, OImageView.class);
		mDrawable = getResources().getDrawable(R.drawable.reward);
		mDrawable.setBounds(0, 0, mDrawable.getIntrinsicWidth(),
				mDrawable.getIntrinsicHeight());
		mDoctorHospital = findViewById(R.id.doctor_hospital_name,
				TextView.class);
		mDoctorPrice = findViewById(R.id.doctor_price, TextView.class);
		try {
			// 初始化年龄
			convertAge(GlobalSettings.sUser.Birth.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 为逻辑判断关键数据
		isBingli = getIntent().getBooleanExtra(Constant.IDENTITY_KEY_BINGLI,
				false);
		isEditBingli = getIntent().getBooleanExtra(
				Constant.IDENTITY_KEY_BINGLI_EDIT, false);
		isEditQuestion = getIntent().getBooleanExtra(
				Constant.IDENTITY_KEY_QUESTION_EDIT, false);
		isCreateCost2Doctor = getIntent().getBooleanExtra(
				Constant.IDENTITY_KEY_CREATE_COST_2_DOCTOR, false);

		init();
		if (isBingli) {
			if (isEditBingli) {
				setNavTitle("编辑病案");
			} else {
				setNavTitle("创建病案");
			}
		} else if (isEditQuestion) {
			setNavTitle("编辑问题");
		} else {
			setNavTitle("创建问题");
		}

		text_right.setTextSize(14);
		setNavRightBtn("创建");
		// text_right.setPadding(, 2, 4, 2);
		text_right.setBackgroundResource(R.drawable.round_btn_orange_create);

		edit_content.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				EditText textView = (EditText) v;
				String hint;
				if (hasFocus) {
					hint = textView.getHint().toString();
					textView.setTag(hint);
					textView.setHint(null);
				} else {
					hint = textView.getTag().toString();
					textView.setHint(hint);
				}
			}
		});

		ll_root.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View view, MotionEvent event) {
				lostFocus();
				return false;
			}
		});

		if (isEditBingli || isEditQuestion) {
			try {
				mr_question = new JSONObject(getIntent().getStringExtra(
						Constant.IDENTITY_KEY));
				mBuweiItemView.setTextValueValue(CommonUtility
						.convertJSONArray2String(
								mr_question.getJSONArray("Part"), ","));
				edit_content.setText(mr_question.getString("Content"));

				JSONArray pics = mr_question.getJSONArray("Pic");
				if (pics.length() > 0) {
					if (CommonUtility.isNull(imgs)) {
						imgs = new HashMap<String, String>();
					}
					int length = pics.length();
					for (int i = 0; i < length; i++) {
						String path = pics.getString(i);
						View view = LayoutInflater.from(activity).inflate(
								R.layout.item_edit_img, null);
						ImageView imgShow = (ImageView) view
								.findViewById(R.id.img_show);
						ImageView imgDelete = (ImageView) view
								.findViewById(R.id.img_delete);
						mBitmapUtils.display(imgShow,
								GlobalSettings.SERVER_IMG_URL + path
										+ Constant.IMG_TH);
						imgDelete.setTag(view);
						imgDelete.setTag(R.id.tag_obj, path);
						imgDelete.setOnClickListener(imgDeletClickListener);
						ll_imgs.addView(view, 0);
						mTextShow.setVisibility(View.GONE);
						imgs.put(path, path);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		if (doctorInfoFromDoctorDetail != null
				&& !doctorInfoFromDoctorDetail.trim().equals("")) {
			try {
				mUser = JsonUtil
						.convert(doctorInfoFromDoctorDetail, User.class);
				if (mUser != null) {
					mDoctorSelector.setVisibility(View.GONE);
					mDoctorSelector1.setVisibility(View.VISIBLE);
					mDoctorName.setText(mUser.Name);
					mDoctorHospital.setText(mUser.Hospital);
					StringBuilder sb = new StringBuilder();
					for (String str : mUser.Professional) {
						sb.append(str).append(",");
					}
					if (sb.length() > 1) {
						mDoctorProfession.setText(sb.replace(sb.length() - 1,
								sb.length(), "").toString());
					}
					mDoctorPrice.setText("￥" + mUser.Cost + "");
					mDoctorPrice.setCompoundDrawables(null, null, null, null);
					mDoctorSelector1.setClickable(false);
					CommonUtility.displayHeadImage(mImg, mBitmapUtils,
							GlobalSettings.SERVER_IMG_URL + mUser.Pic
									+ GlobalSettings.IMG_SRC, getResources(),
							mUser.Sex);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * method desc： 问题描述失去交点
	 */
	void lostFocus() {
		ll_root.setFocusable(true);
		ll_root.setFocusableInTouchMode(true);
		ll_root.requestFocus();
		CommonUtility.hideKeyboard(activity, ll_root);
	}

	public void onClick(View view) {
		super.onClick(view);
		Intent intent = null;
		CommonUtility.hideKeyboard(activity, view);
		int id = view.getId();
		if (id == R.id.img_upload_pic) {
			onClickUploadPic();
		} else if (id == R.id.itemview_buwei) {
			lostFocus();
			startActivityForResult(new Intent(activity, BuweiActivity.class), 0);
		} else if (id == R.id.text_right) {
			buwei = mBuweiItemView.getTextValueValue();
			content = edit_content.getText().toString();
			if (CommonUtility.isNull(content)) {
				CommonUtility.tip(activity, "请输入问题描述");
				return;
			}
			if (content.length() < 20) {
				CommonUtility.tip(activity, "问题描述字数不能少于20字");
				return;
			}
			if (content.length() > 220) {
				CommonUtility.tip(activity, "问题描述字数不能多于220字");
				return;
			}
			uploadPic();
		} else if (id == R.id.text_more_info) {
			if (ll_more_info.isShown()) {
				ll_more_info.setVisibility(View.GONE);
				img_arrow.setImageResource(R.drawable.arrow_down);
			} else {
				ll_more_info.setVisibility(View.VISIBLE);
				img_arrow.setImageResource(R.drawable.arrow_up);
			}
		} else if (id == R.id.itemview_bingshi) {
			intent = new Intent(activity, CommonDataChooseActivity.class);
			String[] datas = { Constant.URL.REQUEST_MEDICALHISTORY_JSON,
					"选择病史", "MedicalHistory",
					CommonDataChooseActivity.TYPE_URL,
					CommonDataChooseActivity.MULITCHOOSE, "" };
			intent.putExtra(Constant.IDENTITY_KEY_1, true);
			intent.putExtra(Constant.IDENTITY_KEY, datas);
			startActivityForResult(intent, 0);
		} else if (id == R.id.itemview_yaowuguomin) {
			intent = new Intent(activity, CommonDataChooseActivity.class);
			String[] datas = { Constant.URL.REQUEST_DRUGALLERGEN_JSON,
					"选择药物过敏", "DrugAllergen",
					CommonDataChooseActivity.TYPE_URL,
					CommonDataChooseActivity.MULITCHOOSE, "" };
			intent.putExtra(Constant.IDENTITY_KEY_1, true);
			intent.putExtra(Constant.IDENTITY_KEY, datas);
			startActivityForResult(intent, 0);
		} else if (id == R.id.itemview_putongguomin) {
			intent = new Intent(activity, CommonDataChooseActivity.class);
			String[] datas = { Constant.URL.REQUEST_ALLERGEN_JSON, "选择普通过敏源",
					"Allergen", CommonDataChooseActivity.TYPE_URL,
					CommonDataChooseActivity.MULITCHOOSE, "" };
			intent.putExtra(Constant.IDENTITY_KEY_1, true);
			intent.putExtra(Constant.IDENTITY_KEY, datas);
			startActivityForResult(intent, 0);
		} else if (id == R.id.itemview_jiaren) {
			intent = new Intent(activity, CommonDataChooseActivity.class);
			String[] datas = { Constant.URL.REQUEST_DISEASE_JSON, "选择家人皮肤病情况",
					"FamilyMedicalHistory", CommonDataChooseActivity.TYPE_URL,
					CommonDataChooseActivity.MULITCHOOSE, "" };
			intent.putExtra(Constant.IDENTITY_KEY_1, true);
			intent.putExtra(Constant.IDENTITY_KEY, datas);
			startActivityForResult(intent, 0);
		} else if (id == R.id.btn_age) {
			ODatePicker datePicker = new ODatePicker(getContext());
			datePicker.show();
			datePicker.setListener(new OnPickDateListener() {

				@Override
				public void onPicked(ODatePicker picker, Date date, String time) {
					convertAge(ODateFormat.format(date, "yyyy"));
				}
			});
		} else if (id == R.id.select_doctor || id == R.id.select_doctor_1) {
			Intent i = new Intent(this, DoctorSelectorActivity.class);
			UserExtra extra = new UserExtra();
			extra.setUser(mUser);
			if (extra.putTo(i)) {
				startActivityForResult(i, REQUEST_FOR_SOLVE_PROBLEM);
			}
		}
	}

	/**
	 * method desc： 点击提交后上传图片，如果图片size > 0
	 * 
	 */
	void uploadPic() {
		if (!CommonUtility.isNull(img_path) && img_path.size() > 0) {
			LoadingProgressExt.showProgressDialog(activity,
					R.string.loading_upload_img);
			for (String path : img_path.values()) {
				HashMap<String, Object> params = new HashMap<String, Object>();
				params.put(Constant.PARAM_TOKEN, GlobalSettings.sToken);
				params.put("pic", new File(path));
				params.put(Constant.PARAM_API, "SYS.UploadPic");
				RequestTaskIntercept.requestIntercept(activity,
						Constant.URL.REQUEST, new RequestHandler(activity,
								callback), false, params);
			}
		} else {
			if (mUser != null && mUser.Cost > 0) {
				// 设悬赏或者选择医生金额大于0进行支付
				Intent intent = new Intent(activity,
						CostOrReward2DoctorActivity.class);
				UserExtra extra = new UserExtra();
				extra.setUser(mUser);
				if (extra.putTo(intent)) {
					startActivityForResult(intent, REQUEST_FOR_PAY_SUCCESS);
				}
			} else {
				// 没有设悬赏或者选择医生直接提交问题
				submitQuestion();
			}
		}
	}

	/**
	 * method desc： 图片上传完后执行问题提交
	 * 
	 */
	void submitQuestion() {
		try {
			text_right.setEnabled(false);
			HashMap<String, Object> params = new HashMap<String, Object>();
			if (isBingli) {
				params.put(Constant.PARAM_API, "MR.Question.Set");
				if (!isEditBingli) {
					params.put("mruid",
							getIntent().getStringExtra(Constant.IDENTITY_KEY));
				} else {
					params.put("qId", mr_question.getString("Qid"));
					params.put("mruid", mr_question.getString("Uid"));
				}
			} else {
				if (isEditQuestion) {
					try {
						params.put("qid", mr_question.getString("Qid"));
					} catch (Exception e) {
					}
				}
				if (mReward) {
					if (mUser != null)
						params.put("Cost", mUser.Cost);
				}
				params.put(Constant.PARAM_API, "Question.Set");
				params.put("Status", 1);
				if (isCreateCost2Doctor) {
					params.put("Status", 2);
					params.put("Is_Appoint", 1);
					// 从医生详情页点击免费咨询按钮传递过来的
					String doctorInfoFromDoctorDetail = getIntent()
							.getStringExtra(Constant.IDENTITY_KEY_DOCTOR_INFO);
					if (!CommonUtility.isNull(doctorInfoFromDoctorDetail)) {
						doctorInfo = new JSONObject(doctorInfoFromDoctorDetail);
						params.put("Doctor_Uid", doctorInfo.getString("Uid"));
						Double cost = doctorInfo.getDouble("Cost");
						if (cost > 0) {
							params.put("Cost", cost);
						}
					} else {
						if (mUser != null) {
							params.put("Doctor_Uid", mUser.Uid);
							if (mUser.Cost > 0) {
								params.put("Cost", mUser.Cost);
							}
						}
					}

				}
			}
			params.put(Constant.PARAM_TOKEN, GlobalSettings.sToken);
			params.put("Part", buwei);
			params.put("MedicalHistory", mBingshiItemView.getTextValueValue());
			params.put("DrugAllergen", mYaowuguominItemView.getTextValueValue());
			params.put("Allergen", mPutongguominItemView.getTextValueValue());
			params.put("FamilyMedicalHistory",
					mJiarenItemView.getTextValueValue());

			if (params.get("Cost") != null && (Double) params.get("Cost") > 0) {
				params.put("PayPwd", GlobalSettings.mPwd);
			}

			params.put("Content", content);

			int checkRadioButtonId = mRadioGroupSex.getCheckedRadioButtonId();
			if (checkRadioButtonId == R.id.radio_male) {
				params.put("Sex", 0);
			} else if (checkRadioButtonId == R.id.radio_fmale) {
				params.put("Sex", 1);
			}

			StringBuilder sbOldPath = new StringBuilder();
			if (!CommonUtility.isNull(imgs) && imgs.size() > 0) {
				StringBuilder sb = new StringBuilder();
				for (String path : imgs.values()) {
					sb.append(path).append(",");
				}
				String path = sb.toString();
				if (path.endsWith(",")) {
					path = path.substring(0, path.length() - 1);
				}
				sbOldPath.append(path);
			}
			if (!CommonUtility.isNull(sbPath)) {
				String path = sbPath.toString();
				if (path.endsWith(",")) {
					path = path.substring(0, path.length() - 1);
				}
				if (!CommonUtility.isNull(sbOldPath)) {
					sbOldPath.append(",");
				}
				sbOldPath.append(path);
			}
			if (!CommonUtility.isNull(sbOldPath)) {
				params.put("Pic", sbOldPath);
			}

			/**
			 * 
			 * 
			 * 
			 * 
			 */

			params.put("Age", mAge);
			RequestTaskIntercept.requestIntercept(activity,
					Constant.URL.REQUEST, new RequestHandler(activity,
							new HandlerCallback() {

								@Override
								public void callback(Object o) {
									text_right.setEnabled(true);
									if (!CommonUtility.isNull(o)) {
										JSONObject object = (JSONObject) o;
										try {
											if (CommonUtility
													.response200(object)) {
												if (isBingli) {
													setResult(Constant.ACTIVITY_CREATE_BINGLI_SUCCESSFULLY);
												} else if (!isEditQuestion) {
													String qid = object
															.getJSONObject(
																	Constant.JSON_PARAM_RES)
															.getString("Qid");
													Intent intent = new Intent(
															activity,
															CreateQuestionSuccessfullyActivity.class);

													intent.putExtra(
															Constant.IDENTITY_KEY,
															// qid
															object.getJSONObject(
																	Constant.JSON_PARAM_RES)
																	.toString());
													startActivity(intent);
												} else if (isEditQuestion
														&& isCreateCost2Doctor) {
													Intent intent = new Intent(
															activity,
															CreateQuestionSuccessAndChatActivity.class);
													object = object
															.getJSONObject(Constant.JSON_PARAM_RES);
													intent.putExtra(
															Constant.IDENTITY_KEY_DOCTOR_INFO,
															doctorInfo
																	.toString());
													intent.putExtra(
															Constant.IDENTITY_KEY,
															object.getString("Qid"));
													startActivity(intent);
													CommonUtility
															.finishActivityFromName(Cost2DoctorActivity.class
																	.getSimpleName());
													CommonUtility
															.finishActivityFromName(Cost2DoctorSuccessActivity.class
																	.getSimpleName());
												}
												Intent intent = new Intent(
														Constant.RECIVER_CHAT_LIST);
												sendBroadcast(intent);
												intent = new Intent(
														Constant.RECIVER_UPDATE_QUESTION);
												sendBroadcast(intent);
												intent = new Intent(
														Constant.RECIVER_QUESTION);
												intent.putExtra(
														Constant.IDENTITY_KEY_1,
														true);
												sendBroadcast(intent);
												finish();
											} else {

												String result = object
														.getString(Constant.JSON_PARAM_RESULTMESSAGE);
												if (result.contains("交易密码错误")) {
													GlobalSettings.mPwd = "";
												}
												CommonUtility.toast(activity,
														result);

											}
										} catch (Exception e) {
											e.printStackTrace();
										}
									}
								}

							}), params);
		} catch (Exception e) {
			text_right.setEnabled(true);
			e.printStackTrace();
		}
	}

	int img_count = 0;
	HandlerCallback callback = new HandlerCallback() {

		@Override
		public void callback(Object o) {
			img_count++;
			if (!CommonUtility.isNull(o)) {
				JSONObject object = (JSONObject) o;
				if (CommonUtility.isNull(sbPath)) {
					sbPath = new StringBuilder();
				}
				try {
					if (CommonUtility.response200(object)) {
						sbPath.append(object.getString(Constant.JSON_PARAM_RES))
								.append(",");
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (img_count >= img_path.size()) {
				LoadingProgressExt.dismiss();
				submitQuestion();
			}
		}
	};

	protected void onClickUploadPic() {
		lostFocus();
		int picCountLeft = (5 + 1) - ll_imgs.getChildCount();
		if (picCountLeft <= 0) {
			CommonUtility.tip(activity, "最多上传5张图片");
			return;
		}
		ArrayList<OActionItem> dataProvider = new ArrayList<OActionSheet.OActionItem>();
		OActionItem item = null;
		item = new OActionItem();
		item.setText("拍照");
		dataProvider.add(item);
		item = new OActionItem();
		item.setText("从手机相册选择");
		dataProvider.add(item);
		OActionSheet<OActionItem> actionSheet = new OActionSheet<OActionSheet.OActionItem>(
				this);
		actionSheet.setCancel("取消");
		actionSheet.setDataProvider(dataProvider);
		actionSheet.show(false, true);
		actionSheet
				.setOnActionItemClickListener(new OnActionItemClickListener<OActionSheet.OActionItem>() {

					@Override
					public void onItemClick(OActionSheet<OActionItem> sheet,
							View v, int position, OActionItem dataItem) {
						if (position == 0) {
							TakePhotoTask task = new TakePhotoTask(
									CreateQuestionActivity.this,
									GlobalSettings.REQUEST_CODE_TAKE_PHOTO);
							task.takePhoto();
							task.setListener(new TakePhotoListener() {

								@Override
								public void onComplete(Uri uri) {
									onPicPhotoComplete(uri.getPath());
								}
							});
						}
						if (position == 1) {
							PickPhotoTask task = new PickPhotoTask(
									CreateQuestionActivity.this,
									GlobalSettings.REQUEST_CODE_PICK_PHOTO);
							task.pickPhoto();
							task.setListener(new PickPhotoListener() {

								@Override
								public void onComplete(Uri uri) {
									onPicPhotoComplete(uri.getPath());
								}
							});
						}
					}
				});
	}

	protected void onPicPhotoComplete(String path) {
		if (CommonUtility.isNull(inflater)) {
			inflater = LayoutInflater.from(activity);
		}
		if (CommonUtility.isNull(img_path)) {
			img_path = new HashMap<View, String>();
		}
		View view = inflater.inflate(R.layout.item_img, null);
		ImageView imgShow = (ImageView) view.findViewById(R.id.img_show);
		ImageView imgDelete = (ImageView) view.findViewById(R.id.img_delete);
		mBitmapUtils.display(imgShow, path);
		imgDelete.setTag(view);
		imgDelete.setOnClickListener(imgDeletClickListener);
		ll_imgs.addView(view, 0);
		mTextShow.setVisibility(View.GONE);
		img_path.put(view, path);
		if (ll_imgs.getChildCount() >= 6) {
			img_upload_pic.setVisibility(View.GONE);
		} else {
			img_upload_pic.setVisibility(View.VISIBLE);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (!CommonUtility.isNull(data)) {
			String value = data.getStringExtra(Constant.IDENTITY_KEY);
			switch (resultCode) {
			case Constant.ACTIVITY_CHOOSE_BUWEI:
				mBuweiItemView.getTextValue().setText(value);
				break;
			case Constant.ACTIVITY_CHOOSEFILE_CODE:
				// see uploadPic
				break;
			default:
				String identity = data.getStringExtra(Constant.IDENTITY_KEY_1);
				if ("MedicalHistory".equals(identity)) {
					mBingshiItemView.setTextValueValue(data
							.getStringExtra(Constant.IDENTITY_KEY));
				} else if ("DrugAllergen".equals(identity)) {
					mYaowuguominItemView.setTextValueValue(data
							.getStringExtra(Constant.IDENTITY_KEY));
				} else if ("Allergen".equals(identity)) {
					mPutongguominItemView.setTextValueValue(data
							.getStringExtra(Constant.IDENTITY_KEY));
				} else if ("FamilyMedicalHistory".equals(identity)) {
					mJiarenItemView.setTextValueValue(data
							.getStringExtra(Constant.IDENTITY_KEY));
				}
				break;
			}

			if (requestCode == REQUEST_FOR_SOLVE_PROBLEM) {
				UserExtra extra = new UserExtra();
				extra.getFrom(data);
				mUser = extra.getUser();
				if (mUser != null) {
					if (mUser.Name.equals("悬赏金额")) {
						mReward = true;
						mDoctorSelector.setVisibility(View.VISIBLE);
						mDoctorSelector1.setVisibility(View.GONE);
						mDoctorSelector
								.setTextValueValue("￥" + mUser.Cost + "");
						mDoctorSelector.setTextTipValue(mUser.Name);
						mDoctorSelector.setCompoundDrawables(mDrawable, null,
								null, null);
					} else {
						mReward = false;
						isCreateCost2Doctor = true;
						mDoctorSelector.setVisibility(View.GONE);
						mDoctorSelector1.setVisibility(View.VISIBLE);
						mDoctorName.setText(mUser.Name);
						mDoctorHospital.setText(mUser.Hospital);
						StringBuilder sb = new StringBuilder();
						for (String str : mUser.Professional) {
							sb.append(str).append(",");
						}
						mDoctorProfession.setText(sb.replace(sb.length() - 1,
								sb.length(), "").toString());
						mDoctorPrice.setText("￥" + mUser.Cost + "");
						CommonUtility.displayHeadImage(mImg, mBitmapUtils,
								GlobalSettings.SERVER_IMG_URL + mUser.Pic
										+ GlobalSettings.IMG_SRC,
								getResources(), mUser.Sex);
					}
				} else {
					mDoctorSelector.setVisibility(View.VISIBLE);
					mDoctorSelector1.setVisibility(View.GONE);
					mDoctorSelector.setTextValueValue("请选择");
					mDoctorSelector.setTextTipValue("指定医生为您进行专业解答");
					mDoctorSelector
							.setCompoundDrawables(null, null, getResources()
									.getDrawable(R.drawable.list_forward), null);
				}
			} else if (requestCode == REQUEST_FOR_PAY_SUCCESS) {
				submitQuestion();
			}
		}
	}

	OnClickListener imgDeletClickListener = new OnClickListener() {

		@Override
		public void onClick(final View view) {
			OAlert alert = new OAlert(view.getContext());
			alert.setOK("确认");
			alert.setCancel("取消");
			alert.setTitle("确定删除图片么？");
			alert.show();
			alert.setListener(new OAlertListener() {

				@Override
				public boolean onOK(OAlert alert) {
					View imgDelete = (View) view.getTag();
					// View imgView = (View) imgDelete.getTag();
					Object path = imgDelete.getTag(R.id.tag_obj);
					if (!CommonUtility.isNull(path)) {
						imgs.remove(path.toString());
					}
					if (!CommonUtility.isNull(img_path)) {
						img_path.remove(imgDelete);
					}

					ll_imgs.removeView(imgDelete);
					if (ll_imgs.getChildCount() < 6) {
						img_upload_pic.setVisibility(View.VISIBLE);
					} else {
						img_upload_pic.setVisibility(View.GONE);
					}
					if (ll_imgs.getChildCount() < 1) {
						mTextShow.setVisibility(View.VISIBLE);
					}
					return false;
				}

				@Override
				public boolean onCancel(OAlert alert) {
					return false;
				}
			});

		}
	};

	void convertAge(String birth) {
		mAge = CommonUtility.getAgeByBirthday(birth);
		mBtnAge.setText("年龄：" + mAge + "岁");
	}

	/*
	 * @Override public void onResume() { super.onResume();
	 * MobclickAgent.onResume(getContext()); }
	 * 
	 * @Override public void onPause() { super.onPause();
	 * MobclickAgent.onPause(getContext()); }
	 */
}
